package zt.song.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import zt.song.filter.CaptchaFilter;
import zt.song.filter.JwtAuthenticationEntryPoint;
import zt.song.security.JwtAccessDeniedHandler;
import zt.song.security.LoginFailureHandler;
import zt.song.security.LoginSuccessHandler;
import zt.song.service.impl.UserDetailsServiceImpl;
/**
 * @Author 宋伟宁
 * @Date 2023/11/21
 * @Version 1.0
 **/
@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;

    @Resource
    private CaptchaFilter captchaFilter;

    @Resource
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;


    @Resource
    private UserDetailsServiceImpl userDetailsService;


    //声明白名单（放过）
    private static final String[] URL_WHITE={
      "/captcha",
      "/login",
            "/pass",
      "/logout"
    };

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //放过验证码
        http.authorizeHttpRequests(resp ->
             resp.requestMatchers(URL_WHITE).permitAll()
                     .anyRequest().authenticated()
        );

        //关闭session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.formLogin(form->
                  form.failureHandler(this.loginFailureHandler)
                          .successHandler(this.loginSuccessHandler)

                );
        //设置UserDetailsService的实现
        http.userDetailsService(this.userDetailsService);
        //未登录
        http.exceptionHandling()
                //未登录
                .authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
                //权限不足
                        .accessDeniedHandler(this.jwtAccessDeniedHandler);
        //先验证码再判断账号和密码
        http//.addFilter(this.jwtAuthenticationFilter)
          .addFilterBefore(this.captchaFilter,UsernamePasswordAuthenticationFilter.class);

        //关闭跨域伪造
        http.csrf().disable();

       return http.build();
    }

}
